(function( $, undefined ) {
$.widget("ui.widgeteditor", {
	/*************************************************************************/
	options: {
		widgetTypes: [],
		widgets: [],
		datatypes: {},
		form: null,
//		formTemplate: '<div class="widgets af-body"></div>',
//		formStylePlaces: ['.af-body'],
		editorTemplate: '<div class="we-rightCol ui-corner-all"><h2>Доступные элементы</h2><div class="widgetTypes"></div></div><div class="we-main"><h1>Редактирование формы</h1><div class="container ui-corner-all"></div></div><div style="clear: both;"></div><div><input type="button" value="Сохранить" class="buttonSave"/></div>',
		widgetTypeTemplate: '<h3><a href="#"></a></h3><div><input type="button" value="Добавить"/><div class="description"></div></div>',
		widgetTemplate: '<div class="ui-corner-all ui-widget ui-widget-content ui-helper-clearfix widget"><div class="header"></div><div class="buttons"><span class="options">O</span><span class="name">N</span><span class="delete">D</span></div><div class="content"></div></div>',
		nameEditorTemplate: '<div title="Название элемента"><input type="text" style="width: 100%;"/></div>',
		widgetDeleteTemplate: '<div title="Удаление элемента">Вы уверены, что хотите удалить этот элемент?</div>',
		optionsEditorTemplate: '<div class="we-optionsEditor"><h2></h2><div class="we-optionsList"></div></div>',
		optionEditorObjectItemTemplate: '<div class="param"><div class="name"></div><div class="isTmpl"></div><div class="enabled"></div><div class="value"></div></div>',
				optionEditorArrayItemTemplate: '<li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s icon"></span><span class="button">редактировать</span></li>',
		optionEditorObjectHeaderTemplate: '<div class="param"><div class="name b">Параметр</div><div class="isTmpl b">Шбл</div><div class="enabled b">Вкл</div><div class="value b" style="padding-top: 4px;">Значение</div></div>',
		optionEditorArrayHeaderTemplate: '<div class="header-name"></div><ul class="sortable"></ul>'
	},
	_create: function() {
		this.element.addClass("widgetEditor");
		this.element.append(this.options.editorTemplate);
		var t=this;
		$(".buttonSave",this.element).button().click( function() {t.save();});

		this.refreshFormName();
		this.refreshWidgetTypes();
		this.refreshFormTemplate();
		this.refreshFormStylePlaces();
		this.refreshWidgets();
	},
	/*************************************************************************/
	_setOption: function(key,value) {
		this.options[key]=value;
		var k1=key.substr(0,1);
		var k2=key.substr(1);
		var name="refresh"+k1.toUpperCase()+k2;
		if (this[name]) this[name]();
	},
	/*************************************************************************/
	refreshFormName: function() {
		$("h1",this.element).text("Редактирование формы '"+this.options.form.name+"'");
	},
	/*************************************************************************/
	refreshFormTemplate: function() {
		// TODO: remove
		$(".container",this.element).append(this.options.form.form_style_editor_body);
	},
	/*************************************************************************/
	refreshFormStylePlaces: function() {
		for (var i=0;i<this.options.formStylePlaces.length;i++) {
			var fsp=this.options.formStylePlaces[i];
			$(fsp.name,this.element).sortable({placeholder: 'placeholder'});
		}
	},
	/*************************************************************************/
	refreshWidgetTypes: function() {
//		$(".available ",this.element).remove();
		var i=0;
		for (i=0;i<this.options.widgetTypes.length;i++) {
			var aw=this.options.widgetTypes[i];
			var item=$(this.options.widgetTypeTemplate).appendTo($(".widgetTypes",this.element));
			$("a",item).text(aw.name);
			$(".description",item).text(aw.description);
			$("input",item).bind("click",
					{place_id: this.options.formStylePlaces[0].id, widget_type_id: aw.id,t:this},
					function(e) {e.data.t.widgetAdd({place_id:e.data.place_id,widget_type_id:e.data.widget_type_id});}
			);
		}
		$(".widgetTypes",this.element).accordion();
	},
	/*************************************************************************/
	getWidgetType: function(widgetTypeId) {
		for (var i=0;i<this.options.widgetTypes.length;i++) {
			var wt=this.options.widgetTypes[i];
			if (wt.id==widgetTypeId) return wt;
		}
		return undefined;
	},
	/*************************************************************************/
	widgetAdd: function(widget) {
		if (!widget.id) {
			widget.id=widget.name='new'+(this.options.widgets.length+1);
		}
		this.options.widgets.push(widget);
		this.buildWidget(widget);
	},
	/*************************************************************************/
	refreshWidgets: function() {
		for (var i=0;i<this.options.widgets.length;i++) {
			this.buildWidget(this.options.widgets[i]);
		}
	},
	/*************************************************************************/
	getFormStylePlace: function(id) {
//		alert(Dumper(this.options.formStylePlaces)+"\nid="+id);
		var i=0;
		var fsp=this.options.formStylePlaces;
		while (i<fsp.length) {
//			alert("fsp[i].id="+fsp[i].id+", id="+id+", == is "+(fsp[i].id==id));
			if (fsp[i].id==id) return fsp[i];
			i++;
		}
		alert("formStylePlace id="+id+" was not found");
		return undefined;
	},
	/*************************************************************************/
	buildWidget: function(widget) {	
		var widgetType=this.getWidgetType(widget.widget_type_id);
		var fsp=this.getFormStylePlace(widget.place_id);
		var div=$(this.options.widgetTemplate).appendTo(fsp.name,this.element);
		widget.div=div;
		div.attr("id","widget-"+widget.id);
		$(".header",div).text(widgetType.name);
		$(".header",div).addClass("ui-widget-header ui-corner-all");//.bind("click",function() {widgets_editor_widget_select(widget)});
		this.widgetSetText(widget);
		$(".buttons .options",div).bind("click",
			{t:this,widget:widget,datatypeId: widgetType.datatype_id},
			function(e) {e.data.t.openEditorDialog(e.data.datatypeId,e.data.widget,"widgetChanged");}
		);
		$(".buttons .name",div).bind("click",
			{t:this,widget:widget},
			function(e) {e.data.t.openNameEditorDialog(e.data.widget);}
		);
		$(".buttons .delete",div).bind("click",
			{t:this,widget:widget},
			function(e) {e.data.t.openWidgetDeleteDialog(e.data.widget);}
		);
	},
	/*************************************************************************/
	widgetChanged: function(widget) {
		this.widgetSetText(widget);
	},
	/*************************************************************************/
	widgetDelete: function(widget) {
		widget.div.remove();
		var i=0;
		while (i<this.options.widgets.length) {
			var w=this.options.widgets[i];
			if (w.id==widget.id) {
				this.options.widgets.splice(i,1);
			} else {
				i++;
			}
		}
	},
	/*************************************************************************/
	openWidgetDeleteDialog: function(widget) {
		var div=$(this.options.widgetDeleteTemplate).appendTo("body");
		var t=this;
		div.dialog({
			width: 400,
			modal: true,
			buttons: [
				{text: "Удалить",click: function() {t.widgetDelete(widget);div.dialog("close");}},
				{text: "Отмена",click: function() {div.dialog("close");}}
			],
			close: function() { div.dialog("destroy");div.remove(); }
		});

	},
	/*************************************************************************/
	openNameEditorDialog: function(widget) {
		var div=$(this.options.nameEditorTemplate).appendTo("body");
		$("input",div).attr("value",widget.name);
		var t=this;
		div.dialog({
			width: 400,
			modal: true,
			buttons: [
				{
					text: "Сохранить",
					click: function() {
						widget.name=$("input",div).attr("value");
						t.widgetChanged(widget);
						div.dialog("close");
					}
				}
			],
			close: function() { div.dialog("destroy");div.remove(); }
		});
	},
	/*************************************************************************/
	openEditorDialog: function(datatypeId,object,callbackFunctionName) {
		var div=$(this.options.optionsEditorTemplate).appendTo("body");
		var datatype=this.options.datatypes[datatypeId];
		div.attr("title","Редактирование параметров '"+datatype.name+"'");
		var buttons=[];
		switch (datatype.group_code) {
			case "array":
				var div2=$(this.options.optionEditorArrayHeaderTemplate).appendTo(div);
				$(".header-name",div).text(datatype.name);
				var ul=$("ul",div);
				if (object && object.array) {
					for (var i=0;i<object.array.length;i++) {
						this.editorDialogAddArrayItem(ul,datatype.array_item_datatype_id,object.array[i]);
					}
				}
				ul.sortable();
				var t=this;
				buttons.push({text: "Добавить",click: function() { t.editorDialogAddArrayItem(ul,datatype.array_item_datatype_id,{}); }});
				buttons.push({text: "Удалить последний",click: function() { }});
				break;
			case "atom":
				break;
			case "object":
				var div2=$(this.options.optionEditorObjectHeaderTemplate).appendTo(div);
				for (var i=0;i<datatype.keys.length;i++) {
					this.editorDialogAddKeyField(div,datatype.keys[i],object);
				}
				break;
		}
		buttons.push({text: "Сохранить",click: function() { $(this).dialog("close"); }});
		buttons.push({text: "Закрыть",click: function() { $(this).dialog("close"); }});
		div.dialog({
			width: 500,
			modal: true,
			buttons: buttons,
			close: function() { div.dialog("destroy");div.remove(); }
		});
	},
	/*************************************************************************/
	editorDialogAddArrayItem: function (sort,datatypeId,object) {
		var datatype=this.options.datatypes[datatypeId];
		var div2=$(this.options.optionEditorArrayItemTemplate).appendTo(sort);
	},
	/*************************************************************************/
	editorDialogAddKeyField: function(div,key,object) {
		var val=object?object[key.key]:undefined;
		var div2=$(this.options.optionEditorObjectItemTemplate).appendTo(div);
		$(".name",div2).text(key.key);
		$('<input type="checkbox"/>').appendTo($(".isTmpl",div2)).attr("checked",val&&val.is_tmpl);
		$('<input type="checkbox"/>').appendTo($(".enabled",div2)).attr("checked",val?true:false).bind("change",
				{t:this,div2:div2,key:key},
				function(e) { e.data.t.editorDialogEnabledSet(e.data.div2,e.data.key,this.checked);}
		);
		switch (key.group_code) {
			case "array":
				var d=$('<input type="button"/>').appendTo($(".value",div2)).attr("value","редактировать массив").button().bind("click",
						{t:this,dtid: key.value_datatype_id},
						function(e) {e.data.t.openEditorDialog(e.data.dtid,null,null);}
				);
				break;
			case "object":
				var d=$('<input type="button"/>').appendTo($(".value",div2)).attr("value","редактировать объект").button();
				break;
			case "atom":
				this.editorDialogAddKeyAtomEditField(div,div2,key,val);
				break;
		}
	},
	/*************************************************************************/
	editorDialogAddKeyAtomEditField: function(div,div2,key,val) {
		switch (key.datatype_code) {
			case "html":
				var d=$('<textarea style="width: 100%;" rows="5"></textarea>').appendTo($(".value",div2));
				if (val) d.attr("value",val.value);
				break;
			default:
				var d=$('<input type="text" style="width: 100%;"/>').appendTo($(".value",div2));
				if (val) d.attr("value",val.value);
		}
		this.editorDialogEnabledSet(div2,key,$(".enabled input",div2).attr("checked"));
	},
	/*************************************************************************/
	editorDialogEnabledSet: function(div2,key,flag) {
		var dis=!flag;
		$('.value textarea',div2).attr("disabled",dis);
		$('.value input',div2).attr("disabled",dis);
		$('.value select',div2).attr("disabled",dis);
	},
	/*************************************************************************/
	widgetSetText: function(w) {
		var s="<div>Название: '"+w.name+"'</div>\n";
		if (w.value) s+="<div>Значение: '"+w.value+"'</div>\n"
		$(".content",w.div).html(s);
	},
	/*************************************************************************/
	save: function() {
		var r={
			form_id: this.options.form.id,
			ajaj: 1,
			mode: "w_save"
		};
		var a=[];
		for (var i=0;i<this.options.formStylePlaces.length;i++) {
			var fsp=this.options.formStylePlaces[i];
			a=a.concat($(fsp.name,this.element).sortable("toArray"));
		}
		r.ordering=a.join(",");
		for (var i=0;i<this.options.widgets.length;i++) {
			var w=this.options.widgets[i];
			r['widget-'+w.id+'-name']=w.name;
			r['widget-'+w.id+'-widget_type_id']=w.widget_type_id;
			r['widget-'+w.id+'-place_id']=w.place_id;
		}

		var rtext=$.ajax({type: "POST",url: "/admin-forms/",data: r,async: false}).responseText;
		
		if (typeof rtext == "string") {
			eval("ret="+rtext+";");
		} else {
			ret=rtext;
		}
		
		if (ret.error_code) {
			$('<div>').appendTo($('body')).attr('title',ret.error_title).html(ret.error).dialog();
		} else if (ret.redirect) {
			document.location=ret.redirect.url;
		} else if (ret.refresh) {
			document.location.reload();
		} else if (ret.call) {
			eval(ret.call+'('+ret+')');
		}
	},
	/*************************************************************************/
	destroy: function() {
	}
});
})(jQuery);

